package henu.action;

import com.opensymphony.xwork2.ActionSupport;

import henu.bean.ManagePerson;
import henu.dao.ManagePersonDao;
import henu.dao.factory.DaoFactory;
import henu.util.AJAX;
import henu.util.CONSTANTS;
import henu.util.Page;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletConfig;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
public class ManagePersonAction extends ActionSupport {
	//文件测试
	private String name;  
	  
    // 上传多个文件的集合文本  
  
    private List<File> upload;  
    // /多个上传文件的类型集合  
    private List<String> uploadContentType;  
   // 多个上传文件的文件名集合  
    private List<String> uploadFileName; 
    
  //文件测试
  	private ServletConfig config = null;
  	private ManagePerson mp;
  	
  	private String uid;
  	private String result;
  	private List<ManagePerson> list;
  	private String orderDirection = "asc";
  	AJAX ajax;
  	private String url = "/admin/ajax.jsp";
  	Page page;
  	private int pageNum = 1;
  	private int numPerPage = 10;
  	private String orderField = "maid";
  	private String property = "-1";
  	private String key = "-1";
  	/*身份证号或手机号*/
  	private String value = null;
  
    public String getName() {  
            return name;  
     }  
  
    public void setName(String name) {  
  
       this.name = name;  
    }  
  
    public List<File> getUpload() {  
  
       return upload;  
    }  
  
    public void setUpload(List<File> upload) {  
  
       this.upload = upload;  
    }  
  
    public List<String> getUploadContentType() {  
  
       return uploadContentType;  
    }  
  
    public void setUploadContentType(List<String> uploadContentType) {  
  
       this.uploadContentType = uploadContentType;  
    }  
  
    public List<String> getUploadFileName() {  
  
       return uploadFileName;  
    }  
  
    public void setUploadFileName(List<String> uploadFileName) {  
  
       this.uploadFileName = uploadFileName;  
    }  
	

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getProperty() {
		return property;
	}

	

	public void setProperty(String property) {
		this.property = property;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getNumPerPage() {
		return numPerPage;
	}

	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}

	public String getOrderField() {
		return orderField;
	}

	public void setOrderField(String orderField) {
		this.orderField = orderField;
	}

	public AJAX getAjax() {
		return ajax;
	}


	public String getUrl() {
		return url;
	}

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public ManagePerson getMp() {
		return mp;
	}

	public void setMp(ManagePerson mp) {
		this.mp = mp;
	}

	public List<ManagePerson> getList() {
		return list;
	}

	public void setList(List<ManagePerson> list) {
		this.list = list;
	}
	
	public String getOrderDirection() {
		return orderDirection;
	}

	public void setOrderDirection(String orderDirection) {
		this.orderDirection = orderDirection;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
	
	public ServletConfig getConfig() {
		return config;
	}

	public void setConfig(ServletConfig config) {
		this.config = config;
	}
	public String add() throws Exception{
		System.out.println("fdsaf");
		ajax=new AJAX();
        ManagePersonDao dao =DaoFactory.getManagePersonDaInstance();
        ManagePerson m = null;
        m = dao.findByMaidOrPhone(mp.getMaid(), mp.getPhone());
        if(m != null){
        	ajax.setStatusCode("300");
			ajax.setMessage("用户已存在，请重新添加");
			ajax.setCallbackType("closeCurrent");
        }else{    
        	   //文件上传
               // 把上传的文件放到指定的路径下  
               String path = ServletActionContext.getServletContext().getRealPath("/upload/managerImages"); 
               // 写到指定的路径中  
               File file = new File(path);  
               // 如果指定的路径没有就创建  
               if (!file.exists()) {  
                   file.mkdirs();  
               }  
               // 把得到的文件的集合通过循环的方式读取并放在指定的路径下  
               for (int i = 0; i < upload.size(); i++) {  
                   try {  
                      //list集合通过get(i)的方式来获取索引  
                	   DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            		   Calendar calendar = Calendar.getInstance();
            		   String fName = df.format(calendar.getTime());
            		   String fileName=fName+uploadFileName.get(i).substring(uploadFileName.get(i).lastIndexOf("."));//系统时间+后缀
                       FileUtils.copyFile(upload.get(i), new File(file, fileName)); 
                       Thread.sleep(1000);
                       if(0!=i){
                    	   mp.setPhoto("upload/managerImages/"+fileName);
               			
                       }else {
                    	   mp.setCopyIdCard("upload/managerImages/"+fileName);
                      }
                  
                   } catch (IOException e){ 
                	   System.out.println("11122");
                      e.printStackTrace();  
                   }
               }  
        	mp.setAudio("在用");
        	mp.setRegistTime(new Date().toLocaleString());
            int result = dao.add(mp);
		    if(result!=0){
			
				ajax.setStatusCode("200");
				ajax.setMessage("添加成功");
				ajax.setNavTabId("managepersoninfo");
				ajax.setCallbackType("closeCurrent");
		    }else{
				ajax.setStatusCode("300");
				ajax.setMessage("添加失败，请重新填写");
		    }
        }
        url="/admin/ajax.jsp";
        return "success";
	}

	public String delete() throws Exception {
		int result = DaoFactory.getManagePersonDaInstance().deleteById(uid);
		ajax = new AJAX();
		if (result != 0) {
			ajax.setStatusCode("200");
			ajax.setMessage("删除成功");
			ajax.setNavTabId("managepersoninfo");
			ajax.setCallbackType("");

		} else {
			ajax.setStatusCode("300");
			ajax.setMessage("删除失败");
			ajax.setNavTabId("managepersoninfo");
			ajax.setCallbackType("");
		}
		url = "/admin/ajax.jsp";
		return SUCCESS;
	}

	public String update() throws Exception {
		 System.out.println("123");
		 ManagePersonDao dao = DaoFactory.getManagePersonDaInstance();
		ajax = new AJAX();
	 	//鏂囦欢涓婁紶
       String path = ServletActionContext.getServletContext().getRealPath("/upload/managerImages"); 
       System.out.println(path);
       File file = new File(path);  
       if (!file.exists()) {  
           file.mkdirs();  
       }
       for (int i = 0; i < upload.size(); i++) {  
           try {  
        	   DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    		   Calendar calendar = Calendar.getInstance();
    		   String fName = df.format(calendar.getTime());
    		   String fileName=fName+uploadFileName.get(i).substring(uploadFileName.get(i).lastIndexOf("."));//绯荤粺鏃堕棿+鍚庣紑
              FileUtils.copyFile(upload.get(i), new File(file, fileName)); 
              Thread.sleep(1000);
               if(0!=i){
            	   mp.setPhoto("upload/managerImages/"+fileName);
       			
               }else {
            	   mp.setCopyIdCard("upload/managerImages/"+fileName);
              }
           } catch (IOException e) {  
              e.printStackTrace();  
           }
       }
		int result = dao.update(uid,mp);
		if (result != 0) {
			ajax.setStatusCode("200");
			ajax.setMessage("修改成功！");
			ajax.setNavTabId("managepersoninfo");
			ajax.setCallbackType("closeCurrent");
		} else {
			ajax.setStatusCode("300");
			ajax.setMessage("修改失败！");
			ajax.setNavTabId("managepersoninfo");
			ajax.setCallbackType("");
		}
		url="/admin/ajax.jsp";
		return SUCCESS;
	}

	/**
	 *  判断登录
	 */
	public String login() throws Exception {
		// 判断数据库中有没有该用户
		ManagePerson m = DaoFactory.getManagePersonDaInstance().login(value, mp.getPassword());
		if (m == null) {
			ServletActionContext.getRequest().getSession().setAttribute("message", "用户名或密码不正确,<a href='/aqjy/admin/Adminlogin.jsp'>点我返回</a>"); 
			url = "../public/message.jsp";
		} else {
			DaoFactory.getManagePersonDaInstance().updateLastTime(m.getMaid());
			ServletActionContext.getRequest().getSession().setAttribute(CONSTANTS.SESSION_ADMIN, m);
			url = "../admin/index.jsp";
		}
		return SUCCESS;
	}

	public String find() throws Exception {
		ManagePersonDao dao = DaoFactory.getManagePersonDaInstance();
		ManagePerson m = dao.findById(uid);
		ActionContext.getContext().put("manageperson", m);
		url = "/admin/managepersonUpdate.jsp";
		return SUCCESS;
	}

	public String findAll() throws Exception {
		page = new Page();
		if (orderField.equals("") || orderDirection.equals("")) {
			orderField = "maid";
			orderDirection = "asc";
		}
		if (property.equals("") || key.equals("")) {
			property = "-1";
			key = "-1";
		}
		page.setProperties("ManagePerson", pageNum, numPerPage, property, key);
//
//		list = DaoFactory.getManagePersonDaInstance()
//				.findByProperty(property, key,orderField, orderDirection,
//						page.getStart(), page.getEnd());
//														
		 ManagePerson m = (ManagePerson) ServletActionContext.getRequest().getSession().getAttribute(CONSTANTS.SESSION_ADMIN);
		//page.setSql("select count(*) from manageperson mp where "+ property + "='" + key + "' and mp='"+ m.getComid() + "'", pageNum,numPerPage);
		list = DaoFactory.getManagePersonDaInstance().findAllByComId(property, key, m.getComid(), orderField, orderDirection, page.getStart(), page.getEnd());
		url = "/admin/managepersonManage.jsp";
		return SUCCESS;
	}

	/*
	 * 退出
	 */
	
	public String exit() throws Exception{
		ServletActionContext.getRequest().getSession().removeAttribute(CONSTANTS.SESSION_ADMIN);
		url="/admin/Adminlogin.jsp";
		return SUCCESS;
	}
}
